import random  # 随机函数
from docx.api import Document
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.section import WD_SECTION
import math

# 多少以内的加减法
MAX_NUMBER = 20
# 生成多少页
PAGES = 5
# 一页多少题，最多100题，超过100题，自行调整格式。
TOTAL_QUESTIONS = 100
# 出题类型, 0-简单模式，只算等号。1-复杂模式，随机计算任意位置数的。
QUESTION_TYPE = 1



def newPage(doc):
    paragraph = doc.add_paragraph()
    run = paragraph.add_run("班级:___年___班         姓名:_________         时间:___分___秒          分数:_________")
    run.font.size = Pt(15)
    doc.add_paragraph("")

    table = doc.add_table(rows=math.ceil(TOTAL_QUESTIONS / 5), cols=5)

    for i in range(len(table.rows)):
        table.rows[i].height = Cm(1.5)

    table.style = 'Table Grid'

    count = 0
    while True:
        a = random.randint(1, MAX_NUMBER)
        b = random.randint(1, MAX_NUMBER)
        operator = random.choice(['+', '-'])

        # 如果是减法运算，确保不生成负数
        if operator == '-' and a < b:
            a, b = b, a

        answer = 0
        if operator == '+':
            if a + b > MAX_NUMBER:
                continue
            answer = a + b
        else:
            answer = a - b

        number_list = [a, b, answer]
        index = 2
        if QUESTION_TYPE == 1:
            index = random.randint(0, 2)
        number_list[index] = "(     )"

        # 计算题目所在的表格行和列
        row = count // 5
        col = count % 5

        # 在表格中添加题目和答案，这里填下划线
        cell = table.cell(row, col)
        cell_text = f"{number_list[0]} {operator} {number_list[1]} = {number_list[2]}"
        cell.text = cell_text
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
        cell.paragraphs[0].runs[0].font.size = Pt(15)
        cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
        cell.paragraphs[0].paragraph_format.line_spacing = 1
        count = count + 1
        if count == TOTAL_QUESTIONS:
            break


def generator():
    doc = Document()
    doc.sections[0].page_height = Cm(29.7)  # 设置A4纸的高度
    doc.sections[0].page_width = Cm(21)  # 设置A4纸的宽
    doc.sections[0].left_margin = Cm(1.5)  # 设置左边距
    doc.sections[0].right_margin = Cm(1.5)  # 设置右边距
    for i in range(PAGES):
        newPage(doc)
        if i < PAGES - 1:
            doc.add_section(start_type=WD_SECTION.NEW_PAGE)

    doc.save("10以内随机数学题.docx")


if __name__ == '__main__':
    generator()
